package com.lauor.test.update;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lauor.smpedr.param.SqlArgMap;
import com.lauor.smpedr.session.SqlSession;
import com.lauor.test.BaseSpringBootUser;
import com.lauor.test.entity.User;
import org.junit.Test;

import java.util.Random;

/**
 * 正常更新
 */
public class NormalUpdateUser extends BaseSpringBootUser {

    //正常更新，更新为空属性
    @Test
    public void updateUser(){
        try {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = sqlSession.selectOne(User.class, null);
            if (user == null) return;
            System.out.println( String.format("old user:%s", JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)) );

            user.setName("new name" + new Random().nextInt(10000));
            user.setIntro(null);
            user.setIconImg( "img".getBytes() );
            System.out.println( String.format("user msg to update:%s", JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)) );
            SqlArgMap sqlArgMap = new SqlArgMap(2);
            sqlArgMap.put("id", user.getId());

            int rows = sqlSession.update(user, sqlArgMap);
            System.out.println( String.format("更新数量:%d", rows) );

            user = sqlSession.selectOne(User.class, null);
            System.out.println( String.format("更新候的数据:%s", JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)) );
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
    //正常更新，不更新为空属性
    @Test
    public void updateUserNotNull(){
        try {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = sqlSession.selectOne(User.class, null);
            if (user == null) return;
            System.out.println( String.format("old user:%s", JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)) );

            user.setName("new name" + new Random().nextInt(10000));
            user.setIconImg(null);
            System.out.println( String.format("user msg to update:%s", JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)) );
            SqlArgMap sqlArgMap = new SqlArgMap(2);
            sqlArgMap.put("id", user.getId());

            int rows = sqlSession.update(user, sqlArgMap, false);
            System.out.println( String.format("更新数量:%d", rows) );

            user = sqlSession.selectOne(User.class, null);
            System.out.println( String.format("更新候的数据:%s", JSON.toJSONString(user, SerializerFeature.WriteMapNullValue)) );
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
